<%--
  Created by IntelliJ IDEA.
  User: 王一同
  Date: 2021/11/20
  Time: 12:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>StorageChart</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/layui/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath}/layui/js/echarts.min.js"></script>
</head>
<body>
<div class="layui-collapse">
    <div class="layui-colla-item">
        <h2 class="layui-colla-title">出入库总金额对比</h2>
        <div class="layui-colla-content layui-show" style="width: 96%;height:70%;">
            <form class="layui-form" lay-filter="formTest">
                <label class="layui-form-label" style="width: 30%">日期范围:</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="test1" placeholder=" 请选择时间 " style="width: 300px">
                </div>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn" lay-submit=""  id="serachBtn" style="margin-left: 6px;">立即查询</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </form>
            <br/>
            <div id="box1" style="width: 98%;height: 80%"></div>
                <div id="box3" style="width: 98%;height: 5%;text-align: center">
                    <span style="font-size: 16px;">盈利状态：
                        <span id="box3_1" style="font-size: 16px;"></span>
                    </span>
                </div>
        </div>
    </div>
    <div class="layui-colla-item">
        <h2 class="layui-colla-title">用户购买排行</h2>
        <div class="layui-colla-content layui-show" style="width: 96%;height:80%;">
            <form>
                <div class="layui-form-item">
                    <div class="layui-inline" style="margin-left: 13%">
                        <label class="layui-form-label" style="width: 96.5px;">客户数量：</label>
                        <div class="layui-input-inline">
                            <input type="tel" name="cpname"  id="cpname" autocomplete="off" placeholder=" 请输入您想查询的用户前几名(例如：10) " class="layui-input" style="width: 300px">
                        </div>
                        <label class="layui-form-label" style="width: 120px;padding-left: 100px" >订单日期范围:</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" name="crdate" id="test2" placeholder=" 请选择时间 " style="width: 300px">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item" style="padding-left: 32%">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" lay-submit=""  id="serachBtn1" lay-filter="demo1">立即查询</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>

            <div id="box2" style="width: 98%;height: 80%"></div>
        </div>
    </div>
</div>

</body>
<script>
    //js方式获取本地时间+1天
    Date.prototype.toLocaleStringTomorrow = function() {
        var dateTime=new Date();
        dateTime=dateTime.setDate(dateTime.getDate()+1);
        dateTime=new Date(dateTime);
        var y = dateTime.getFullYear();
        var m = dateTime.getMonth()+1;
        m = m<10?'0'+m:m;
        var d = dateTime.getDate();
        d = d<10?("0"+d):d;
        return y+"-"+m+"-"+d;
    }

    layui.use(['laydate','layer','jquery','element'],function () {
        var element = layui.element;
        var layer = layui.layer;
        var $ = layui.$;
        var laydate = layui.laydate;
        var tomorrowTime = (new Date()).toLocaleStringTomorrow();

        $(function () {
            value1="";
            value2="";
            value3 = "";
            showChartOne();
            showChartTwo();
        })

        //日期选择器(出入库金额)
        var value1;
        laydate.render({
            elem: '#test1'
            ,type: 'datetime'
            ,range: true
            ,max:tomorrowTime
            //每次点击清空之前的日期选择
            ,ready:function(){
                value1 = "";
            }
            ,done: function(value) {
                value1 = value;
            }
        });
        var value2;
        laydate.render({
            elem: '#test2'
            ,type: 'datetime'
            ,range: true
            ,max:tomorrowTime
            //每次点击清空之前的日期选择
            ,ready:function(){
                value2 = "";
            }
            ,done: function(value) {
                value2 = value;
            }
        });

        //根据时间查询(出入库金额)
        $("#serachBtn").on("click",function () {
            if (value1 == "" || value1 == undefined){
                value1 = "";
            }
            showChartOne();
        });

        //根据时间查询用户
        var value3;
        $("#serachBtn1").on("click",function () {
            var value = $("#cpname").val();
            if (value2 != "" && value==""){
               if (value2 == undefined){
                    value2 = "";
                }
            }
            if (value2 == "" && value != "") {
                if (value == undefined || !(/(^[1-9]\d*$)/.test(value))) {
                    value3 = "";
                    layer.msg("请输入正确的用户排行查询格式，例如5或10", {icon: 5});
                } else {
                    value3 = value;
                }
            }
            if (value2 != "" && value != ""){
               if (value2 == undefined){
                    value2 = "";
                }
                if (value == undefined || !(/(^[1-9]\d*$)/.test(value))) {
                    value3 = "";
                    layer.msg("请输入正确的用户排行查询格式，例如5或10", {icon: 5});
                } else {
                    value3 = value;
                }
            }
            showChartTwo();
        });

        var show;
        function tip(a,str) {
            //在你掉接口拿数据去渲染chart图标的时候，渲染数据的时候判断一下
            if(a[0].value===null && a[1].value===null){
                show=str;
                $("#box3_1").html('<i class="layui-icon layui-icon-face-cry" style="font-size: 16px; color: red;">暂无数据</i>');
            }else {
                show='仅包含审核通过的订单';
            }
        }

        //出入库金额表
        function showChartOne() {
            var chartDom = document.getElementById('box1');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
                title: {
                    text: '出入库总金额对比',
                    subtext: '',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                toolbox: {
                    feature: {
                        dataView: {show: true, readOnly: false},
                        saveAsImage: {show: true}
                    }
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                },
                series: [
                    {
                        name: '金额详情',
                        type: 'pie',
                        radius: '50%',
                        data: [],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };

            option && myChart.setOption(option);
            /*            myChart.showLoading();    //数据加载完之前先显示一段简单的loading动画*/

            //console.log(value1);
            let sumPrice;
            $.ajax({
                type : "post",
                async : true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
                url : "${pageContext.request.contextPath}/bookChart/queryPriceCount",    //请求发送到TestServlet处
                data: {"valuedate":value1},
                success : function(result) {
                    sumPrice=parseFloat(result[1].value-result[0].value).toFixed(2);
                    if (sumPrice>0){
                        $("#box3_1").html('<i class="layui-icon layui-icon-face-smile" style="font-size: 16px; color: green;">盈利状态，赚了<i class="layui-icon layui-icon-rmb"  style="font-size: 20px; color: green;">'+sumPrice+'元</i></i>');
                    }else if (sumPrice==0){
                        $("#box3_1").html('<i class="layui-icon layui-icon-face-surprised" style="font-size: 16px; color: goldenrod;">成长状态，不赔不赚<i class="layui-icon layui-icon-rmb"  style="font-size: 20px; color: goldenrod;">'+sumPrice+'元</i></i>');
                    }else if (sumPrice<0){
                        $("#box3_1").html('<i class="layui-icon layui-icon-face-cry" style="font-size: 16px; color: red;">亏损状态，亏了<i class="layui-icon layui-icon-rmb"  style="font-size: 20px; color: red;">'+Math.abs(sumPrice)+'元</i></i>');
                    }
                    tip(result,"您查询的时间范围内暂无出入库数据");
                    myChart.setOption({        //填入数据
                        title:{
                            subtext:show
                        },
                        legend: {
                            data: result.name
                        },
                        series: [{
                            data: (function(){
                                var rs = [];
                                for(var res=0;res<result.length;res++){
                                    rs.push({
                                        name :result[res].name,
                                        value:result[res].value
                                    });
                                }
                                return rs;
                            })()
                        }]
                    });
                },
                error : function() {
                    //请求失败时执行该函数
                    layer.msg("出入库金额图表请求数据失败!",{icon:5});
                    myChart.hideLoading();
                }
            });
        };

        //库存表
        function showChartTwo() {
            var myChart = echarts.init(document.getElementById('box2'));
            // 显示标题，图例和空的坐标轴
            myChart.setOption({
                title: {
                    text: '用户购买排行',
                    subtext: '',
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                toolbox: {
                    feature: {
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        saveAsImage: {show: true}
                    }
                },
                dataZoom:
                    [
                        {type: 'inside'},        //用于添加滚轮缩放
                        {type:'slider' },  //用于添加滑动条缩放，
                    ],
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        rotate: 45,
                    },
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    data: [],
                    type: 'bar',
                    showBackground: true,
                    backgroundStyle: {
                        color: 'rgba(180, 180, 180, 0.2)'
                    }
                }]
            });

            myChart.showLoading();    //数据加载完之前先显示一段简单的loading动画

            var names=[];    //类别数组（实际用来盛放X轴坐标值）
            var nums=[];    //销量数组（实际用来盛放Y坐标值）
            $.ajax({
                type : "post",
                async : true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
                url : "${pageContext.request.contextPath}/bookChart/queryUserCount",    //请求发送到TestServlet处
                data: {"datevalue":value2,"uservalue":value3},
                success : function(result) {
                    //请求成功时执行该函数内容，result即为服务器返回的json对象
                        for(var i=0;i<result.length;i++){
                            names.push(result[i].pname);    //挨个取出类别并填入类别数组
                        }
                        for(var i=0;i<result.length;i++){
                            //  nums.push(result[i].productionArrangement.number);    //挨个取出销量并填入销量数组daliy
                            nums.push(result[i].c);
                        }
                        var show1;
                        //在你掉接口拿数据去渲染chart图标的时候，渲染数据的时候判断一下
                        if(names.length===0 && nums.length===0){
                            show1='您查询的时间范围内暂无用户购买数据';
                        }else {
                            show1='仅包含用户待发货和已发货的订单';
                        }

                        myChart.hideLoading();    //隐藏加载动画
                            myChart.setOption({        //加载数据图表
                                title:{
                                    subtext:show1
                                },
                                xAxis: {
                                    data: names
                                },
                                series: [
                                    {
                                        // 根据名字对应到相应的系列
                                        name: names,
                                        data: nums,
                                        itemStyle: {
                                            normal: {
                                                //这里是重点
                                                color:function() {
                                                    //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
    /*                                              var colorList = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622'];
                                                    for (var i=0;i<nums.length;i++){
                                                        if (nums[i]>1){
                                                            return colorList[5];
                                                        }
                                                    }*/
                                                    //随机显示
                                                    return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);
                                                }
                                            }
                                        }
                                    },
                                ]
                            });
                        },
                    error : function() {
                        //请求失败时执行该函数
                        layer.msg("客户购物排行图表请求数据失败!",{icon:5});
                        myChart.hideLoading();
                    }
                });
            };
    });
</script>
</html>
